'use client'

import { useState, useEffect } from 'react'
import {
  DocumentTextIcon,
  FilmIcon,
  CodeBracketIcon,
  DocumentIcon,
  ArrowUpTrayIcon,
  TrashIcon,
  EyeIcon,
  LinkIcon,
} from '@heroicons/react/24/outline'
import Button from '@/components/ui/Button'
import { PrismaAdapter } from '@next-auth/prisma-adapter'

interface Resource {
  id: string
  title: string
  type: string
  url: string
  createdAt: string
}

interface ResourceUploaderProps {
  experimentId: string
  resources: Resource[]
  onResourceAdded?: (resource: Resource) => void
  onResourceDeleted?: (resourceId: string) => void
  canManage?: boolean
}

export default function ResourceUploader({
  experimentId,
  resources = [],
  onResourceAdded,
  onResourceDeleted,
  canManage = false,
}: ResourceUploaderProps) {
  const [files, setFiles] = useState<File[]>([])
  const [resourceType, setResourceType] = useState('DOCUMENT')
  const [uploading, setUploading] = useState(false)
  const [error, setError] = useState('')
  const [linkUrl, setLinkUrl] = useState('')
  const [linkTitle, setLinkTitle] = useState('')

  useEffect(() => {
    if (resourceType === 'LINK') {
      setFiles([]);
    } else {
      setLinkUrl('');
      setLinkTitle('');
    }
  }, [resourceType]);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (resourceType === 'LINK') return;
    if (e.target.files && e.target.files.length > 0) {
      setFiles(Array.from(e.target.files))
    }
  }

  const handleUpload = async () => {
    setError('')

    if (resourceType === 'LINK') {
      if (!linkUrl.trim()) {
        setError('请输入有效的链接地址');
        return;
      }
      if (!linkTitle.trim()) {
        setError('请输入链接的标题');
        return;
      }
    } else {
      if (files.length === 0) {
        setError('请选择文件');
        return;
      }
    }

    setUploading(true);

    let resourceDataToSave: {
      title: string;
      type: string;
      url: string;
      experimentId: string;
    };

    try {
      if (resourceType === 'LINK') {
        resourceDataToSave = {
          title: linkTitle,
          type: resourceType,
          url: linkUrl,
          experimentId: experimentId,
        };
      } else {
        const file = files[0];
        const formData = new FormData();
        formData.append('file', file);
        formData.append('experimentId', experimentId);

        const uploadResponse = await fetch('/api/upload', {
          method: 'POST',
          body: formData,
        });

        const uploadData = await uploadResponse.json();

        if (!uploadResponse.ok) {
          throw new Error(uploadData.message || uploadData.error || '文件上传失败');
        }
        resourceDataToSave = {
          title: uploadData.fileName || file.name,
          type: resourceType,
          url: uploadData.fileUrl,
          experimentId: experimentId,
        };
      }

      const saveResourceResponse = await fetch(`/api/experiments/${experimentId}/resources`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(resourceDataToSave),
      });

      const savedResourceData = await saveResourceResponse.json();

      if (!saveResourceResponse.ok) {
        throw new Error(savedResourceData.message || savedResourceData.error || '保存资源记录失败');
      }

      if (onResourceAdded) {
        onResourceAdded(savedResourceData.resource); 
      }
      
      setFiles([]);
      setLinkUrl('');
      setLinkTitle('');
      setError('');
    } catch (err: any) {
      setError(err.message || '操作失败');
    } finally {
      setUploading(false);
    }
  }

  const handleDelete = async (resourceId: string) => {
    if (!window.confirm('确定要删除这个资源吗？')) return;
    try {
      const response = await fetch(`/api/resources/${resourceId}`, {
        method: 'DELETE',
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.message || data.error || '删除失败');
      }

      if (onResourceDeleted) {
        onResourceDeleted(resourceId);
      }
      setError('');
    } catch (err: any) {
      setError(err.message || '删除失败');
    }
  };

  const getResourceIcon = (type: string) => {
    switch (type) {
      case 'DOCUMENT':
        return <DocumentTextIcon className="h-6 w-6 text-gray-500" />
      case 'VIDEO':
        return <FilmIcon className="h-6 w-6 text-gray-500" />
      case 'CODE':
        return <CodeBracketIcon className="h-6 w-6 text-gray-500" />
      case 'IMAGE':
        return <DocumentIcon className="h-6 w-6 text-gray-500" />
      case 'LINK':
        return <LinkIcon className="h-6 w-6 text-gray-500" />
      default:
        return <DocumentIcon className="h-6 w-6 text-gray-500" />
    }
  }

  return (
    <div className="space-y-6">
      {canManage && (
        <form
          className="bg-white p-6 rounded-lg shadow border border-gray-200 space-y-4"
        >
          <h3 className="text-xl font-semibold text-gray-900">上传新的实验资源</h3>
          
          {error && (
            <div className="mb-4 rounded-md bg-red-50 p-4">
              <div className="text-sm text-red-700">{error}</div>
            </div>
          )}

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label htmlFor="resourceType" className="block text-sm font-medium text-gray-700">
                资源类型
              </label>
              <select
                id="resourceType"
                value={resourceType}
                onChange={(e) => setResourceType(e.target.value)}
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
              >
                <option value="DOCUMENT">文档 (PDF, Word, PPT等)</option>
                <option value="VIDEO">视频 (MP4, MOV等)</option>
                <option value="CODE">代码 (ZIP, PY, JS等)</option>
                <option value="IMAGE">图片 (JPG, PNG等)</option>
                <option value="LINK">外部链接</option> 
                <option value="OTHER">其他</option>
              </select>
            </div>

            {resourceType === 'LINK' ? (
              <div className="md:col-span-2 grid grid-cols-1 gap-6">
                 <div>
                    <label htmlFor="linkTitle" className="block text-sm font-medium text-gray-700">链接标题 <span className="text-red-500">*</span></label>
                    <input 
                        type="text" 
                        id="linkTitle"
                        placeholder="例如：实验参考资料"
                        value={linkTitle}
                        onChange={(e) => setLinkTitle(e.target.value)}
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                        required
                    />
                </div>
                <div>
                    <label htmlFor="link-url" className="block text-sm font-medium text-gray-700">链接地址 <span className="text-red-500">*</span></label>
                    <input 
                        type="url" 
                        id="link-url"
                        placeholder="https://example.com/resource"
                        value={linkUrl}
                        onChange={(e) => setLinkUrl(e.target.value)}
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                        required
                    />
                </div>
              </div>
            ) : (
              <div>
                <label htmlFor="file-upload" className="block text-sm font-medium text-gray-700">
                  选择文件 <span className="text-red-500">*</span>
                </label>
                <div className="mt-1">
                  <input
                    id="file-upload"
                    name="file-upload"
                    type="file"
                    className="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border file:border-gray-300 file:text-sm file:font-medium file:bg-gray-50 file:text-gray-700 hover:file:bg-gray-100"
                    onChange={handleFileChange}
                    multiple
                  />
                </div>
              </div>
            )}
          </div>

          {files.length > 0 && resourceType !== 'LINK' && (
            <div className="mt-4">
              <h4 className="text-sm font-medium text-gray-700 mb-1">已选择的文件：</h4>
              <ul className="space-y-1 max-h-32 overflow-y-auto">
                {files.map((file, index) => (
                  <li key={index} className="text-xs text-gray-600 bg-gray-50 p-1 rounded">
                    {file.name} ({(file.size / 1024).toFixed(1)} KB)
                  </li>
                ))}
              </ul>
            </div>
          )}

          <div className="flex justify-end pt-4">
            <Button 
              type="button"
              onClick={handleUpload} 
              disabled={uploading || (resourceType !== 'LINK' && files.length === 0) || (resourceType === 'LINK' && (!linkUrl.trim() || !linkTitle.trim())) }
            >
              {uploading ? '处理中...' : '添加资源'}
            </Button>
          </div>
        </form>
      )}

      {(resources && resources.length > 0) ? (
        <div className="bg-white p-4 sm:p-6 rounded-lg shadow border border-gray-200 mt-6">
          <h3 className="text-xl font-semibold text-gray-900 mb-4">
            {canManage ? '已上传的实验资源' : '实验资源列表'}
          </h3>
          <ul className="divide-y divide-gray-200">
            {resources.map((resource) => (
              <li key={resource.id} className="py-4 flex flex-col sm:flex-row justify-between items-start sm:items-center">
                <div className="flex items-center mb-2 sm:mb-0">
                  {getResourceIcon(resource.type)}
                  <div className="ml-4">
                    <p className="text-md font-medium text-gray-900">{resource.title}</p>
                    <p className="text-xs text-gray-500 uppercase tracking-wider">{resource.type}</p>
                  </div>
                </div>
                <div className="flex space-x-3 flex-shrink-0 self-end sm:self-center">
                  <a
                    href={resource.url}
                    target="_blank"
                    rel="noreferrer"
                    className="inline-flex items-center px-3 py-1.5 border border-gray-300 text-xs font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
                  >
                    <EyeIcon className="h-4 w-4 mr-1.5" />
                    查看/下载
                  </a>
                  {canManage && (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleDelete(resource.id)}
                      className="text-red-600 hover:text-red-700 hover:bg-red-50 border-red-300 hover:border-red-400"
                    >
                      <TrashIcon className="h-4 w-4 mr-1.5" />
                      删除
                    </Button>
                  )}
                </div>
              </li>
            ))}
          </ul>
        </div>
      ) : (
        <div className="text-center py-6 bg-gray-50 rounded-lg mt-6">
            <DocumentIcon className="mx-auto h-12 w-12 text-gray-400" />
            <h3 className="mt-2 text-sm font-medium text-gray-900">暂无实验资源</h3>
            {canManage && <p className="mt-1 text-sm text-gray-500">您可以上传相关文件、代码或链接。</p>}
        </div>
      )}
    </div>
  )
} 